package com.neutech.dao.impl;

import com.neutech.constant.Constant;
import com.neutech.dao.DeliveryAddressDAO;
import com.neutech.entity.DeliveryAddress;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DeliveryAddressDAOImpl implements DeliveryAddressDAO {
    @Override
    public List<DeliveryAddress> listByUserId(Integer userId) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<DeliveryAddress> deliveryAddressList = new ArrayList<>();

        try {
            connection = Constant.DATASOURCE.getConnection();
            String sql = "select * from deliveryaddress where userId = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,userId);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                DeliveryAddress deliveryAddress = new DeliveryAddress();
                deliveryAddress.setId(resultSet.getInt("daId"));
                deliveryAddress.setContactName(resultSet.getString("contactName"));
                deliveryAddress.setSex(resultSet.getString("contactSex"));
                deliveryAddress.setPhone(resultSet.getString("contactTel"));
                deliveryAddress.setAddress(resultSet.getString("address"));
                deliveryAddress.setUserId(resultSet.getInt("userId"));

                deliveryAddressList.add(deliveryAddress);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return deliveryAddressList;
    }
}
